import 'dart:io';

import 'package:flutter/material.dart';

class NUploadButton extends StatefulWidget {
  const NUploadButton({
    super.key,
    required this.path,
    this.urlBlock,
    this.onDelete,
    this.radius = 8,
  });

  /// 文件本地路径
  final String path;

  /// 上传成功获取 url 回调
  final ValueChanged<String>? urlBlock;

  /// 返回删除元素的 id
  final VoidCallback? onDelete;

  /// 圆角 默认8
  final double radius;

  @override
  _NUploadButtonState createState() => _NUploadButtonState();
}

class _NUploadButtonState extends State<NUploadButton> {
  /// 防止触发多次上传动作
  var _isLoading = false;

  /// 请求成功或失败
  final _successVN = ValueNotifier(true);

  /// 上传进度
  final _percentVN = ValueNotifier(0.0);

  @override
  void initState() {
    // TODO: implement initState
    onRefresh();
    super.initState();
  }

  @override
  void didUpdateWidget(covariant NUploadButton oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    // debugPrint("didUpdateWidget:${widget.path == oldWidget.path}");
    if (widget.path == oldWidget.path) {
      // BrunoUtil.showInfoToast("path相同");
      return;
    }

    onRefresh();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      fit: StackFit.expand,
      children: [
        ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(widget.radius)),
          child: Image.file(
            File(widget.path),
            fit: BoxFit.cover,
          ),
        ),
        Positioned(
          top: 0,
          right: 0,
          bottom: 0,
          left: 0,
          child: buildUploading(),
        ),
      ],
    );
  }

  Widget buildUploading() {
    return AnimatedBuilder(
        animation: Listenable.merge([
          _successVN,
          _percentVN,
        ]),
        builder: (context, child) {
          if (_successVN.value == false) {
            return buildUploadFail();
          }

          final value = _percentVN.value;
          if (value >= 1) {
            return const SizedBox();
          }
          return Container(
            color: Colors.black45,
            alignment: Alignment.center,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '$value.toStringAsPercent(2)',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                  ),
                ),
                const Text(
                  "上传中",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                  ),
                )
              ],
            ),
          );
        });
  }

  Widget buildUploadFail() {
    return Stack(
      children: [
        InkWell(
          onTap: () {
            debugPrint("onTap");
            onRefresh();
          },
          child: Container(
            color: Colors.black45,
            // margin: EdgeInsets.only(top: 12, right: 12),
            alignment: Alignment.center,
            child: const Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(Icons.refresh, color: Colors.red),
                Text(
                  "点击重试",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                  ),
                )
              ],
            ),
          ),
        ),
        Positioned(
          top: 0,
          right: 0,
          child: IconButton(
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(),
            onPressed: widget.onDelete,
            icon: const Icon(
              Icons.cancel,
              color: Colors.red,
            ),
          ),
        ),
      ],
    );
  }

  Future<String?> uploadImage({
    required String path,
  }) async {
    // 上传url
    String uploadUrl = '图片存储地址';
    // var res = await RequestManager.upload(uploadUrl, path,
    //     onSendProgress: (int count, int total) {
    //   _percentVN.value = (count / total);
    //   // debugPrint("${count}/${total}_${_percentVN.value}_${_percentVN.value.toStringAsPercent(2)}");
    // });
    var res = {};
    if (res['code'] == 'OK') {
      debugPrint("res: $res");
    }
    return res['result'];
  }

  onRefresh() {
    debugPrint("onRefresh");
    if (_isLoading) {
      debugPrint("_isLoading: $_isLoading");
      return;
    }
    _isLoading = true;
    _successVN.value = true;
    uploadImage(
      path: widget.path,
    ).then((value) {
      if (value?.isNotEmpty == false) {
        _successVN.value = false;
        debugPrint("上传失败:${widget.path}");
        return;
      }
      _successVN.value = true;
      widget.urlBlock?.call(value!);
    }).catchError((err) {
      debugPrint("err:$err");
      _successVN.value = false;
    }).whenComplete(() {
      _isLoading = false;
    });
  }
}

class NUploadModel<T> {
  NUploadModel({
    required this.data,
    this.url,
  });

  /// 上传之后的文件 url
  String? url;

  /// 挂载数据,一般是模型
  T data;
}
